package javacommon.util;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;

/**
 * 获取IP的工具类
 * <p>
 * Copyright: Copyright (c) 2011 4 28 10:58:08
 * <p>
 * Company: 北京品友互动信息技术有限公司
 * <p>
 * Author: wen.lv@ipinyou.com
 * <p>
 * Version: 1.0
 * <p>
 */
public class IpHelper {
	
	private static String getIpFromCookie(HttpServletRequest request){
		Cookie[] cookies = request.getCookies();
		if(cookies == null){
			return null;
		}
		for(Cookie c:cookies){
			if("ip".equals(c.getName())){
				return c.getValue().trim();
			}
		}
		return null;
	}
	
	public static String getIpAddr(HttpServletRequest request) {
		String ip = getIpFromCookie(request);
		if (!StringUtils.isEmpty(ip)) {
			return ip;
		}else{
			ip = request.getHeader("X-Real-IP");
		}

		if (StringUtils.isEmpty(ip) || ip.toLowerCase().contains("unknown")) {
			ip = request.getHeader("x-forwarded-for");
		}else if(ip.contains(",")){
			String[] ips = ip.split(",");
			if (ips.length > 0) {
				return ips[ips.length - 1];
			}	
		}else{
			return ip;
		}
		

		// "unknown".equalsIgnoreCase(ip)
		if (StringUtils.isEmpty(ip) || ip.toLowerCase().contains("unknown")) {
			ip = request.getHeader("Proxy-Client-IP");
		}else{
			return ip;
		}

		if (StringUtils.isEmpty(ip) || ip.toLowerCase().contains("unknown")) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}else{
			return ip;
		}

		if (StringUtils.isEmpty(ip) || ip.toLowerCase().contains("unknown")) {
			return request.getRemoteAddr();
		}else{
			return ip;
		}
	}

	public static String getServerIp(){
		String result="";
		String temp="";
		Enumeration<NetworkInterface> netInterfaces = null;  
		try {  
		    netInterfaces = NetworkInterface.getNetworkInterfaces();  
		    while (netInterfaces.hasMoreElements()) {  
		        NetworkInterface ni = netInterfaces.nextElement();   
		        Enumeration<InetAddress> ips = ni.getInetAddresses();  
		        while (ips.hasMoreElements()) { 
		        	String ip=ips.nextElement().getHostAddress();
		        	if(ip.startsWith("192")){
		        		temp=ip;
		        	}
		          
		        }  
		    }  
		} catch (Exception e) {  
			System.out.println("不能获取服务器ip");
		}  
	     String[] ss=temp.split("\\.");
	     for(int i=0;i<ss.length;i++){
	    	int len= 3-ss[i].length();
	    	String zero="";
	    	for(int j=0;j<len;j++){
	    		zero+="0";
	    	}
	    	result+=(zero+ss[i]);
	     }
	     
	     return result;
	}
}
